package com.tywj.navigation.city

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.tywj.lib.core.common.extension.onClick
import com.tywj.navigation.R
import com.tywj.navigation.api.NavigationApi
import com.tywj.navigation.entity.CityEntity
import com.tywj.navigation.route.NavigationRoute
import com.tywj.navigation.tool.MapTool
import com.tywj.panda.customer.common.http.PDArrayCallback
import com.tywj.panda.customer.common.tool.PermissionTool
import com.tywj.panda.customer.common.view.base.MyBaseActivity
import kotlinx.android.synthetic.main.navigation_activity_choose_city.*

/**
 * 选择城市
 */
@Route(path = NavigationRoute.NAVIGATION_SELECTED_CITY)
class ChooseCityActivity : MyBaseActivity() {

    companion object {
        const val PARAMS_CITY = "city"
    }

    private lateinit var adapter: CityAdapter

    private var currentCity = MapTool.CITY_DEFAULT

    private var mLocationListener: AMapLocationListener? = null

    //获取当前位置
    private var mLocationClient: AMapLocationClient? = null
    private var mLocationOption: AMapLocationClientOption? = null

    override fun getLayoutID(): Int = R.layout.navigation_activity_choose_city

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)

        //初始化定位
        mLocationClient = AMapLocationClient(this)
        mLocationOption = AMapLocationClientOption()


        mLocationListener = AMapLocationListener { aMapLocation ->
            aMapLocation?.let {
                if (it.city.isNotEmpty()) {
                    currentCity = it.city
                }
                tvCurrentCity.text = currentCity
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        initRecycleView()

        tvCurrentCity.text = currentCity

        swipeRefreshLayout.setColorSchemeResources(R.color.common_yellow_FE)
    }

    override fun initListener() {
        super.initListener()

        statusLayout.setOnEmptyLayoutButtonClick {
            loadData()
        }

        statusLayout.setOnErrorLayoutButtonClick {
            // 重新加载数据
            loadData()

        }

        swipeRefreshLayout.setOnRefreshListener {
            // 刷新首页数据
            loadData()

        }

        tvCurrentCity.onClick {
            val bean = CityEntity()
            bean.cityName = currentCity
            returnSelectedCity(bean)
        }

        adapter.setOnItemClickListener { _, _, position ->
            returnSelectedCity(adapter.data[position])
        }
    }

    override fun onResumeEveryTime() {
        super.onResumeEveryTime()
        PermissionTool.location(this) {}
    }

    override fun onResume() {
        super.onResume()
        startGetMyCurrentLocation()
    }

    override fun loadDataOnCreate() {
        super.loadDataOnCreate()
        loadData()
    }

    private fun loadData() {
        statusLayout.showLoadingLayout()
        NavigationApi.getCityList().attachToLifecycle(this)
            .execute(object : PDArrayCallback<CityEntity>(
                CityEntity::class.java
            ) {
                override fun success(data: ArrayList<CityEntity>) {
                    handleData(data)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    statusLayout.showErrorLayoutByCode(code, message)
                }

                override fun onComplete() {
                    super.onComplete()

                    swipeRefreshLayout.isRefreshing = false
                }
            })
    }

    private fun handleData(list: ArrayList<CityEntity>) {
        if (list.isEmpty()) {
            statusLayout.showEmptyLayout()
        } else {
            statusLayout.showContentLayout()
        }
        adapter.setNewData(list)
    }


    private fun initRecycleView() {
        adapter = CityAdapter()
        rvList.layoutManager = LinearLayoutManager(this)
        rvList.adapter = adapter
    }

    private fun returnSelectedCity(bean: CityEntity) {
        val intent = Intent()
        intent.putExtra(PARAMS_CITY, bean)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    //得到当前位置
    private fun startGetMyCurrentLocation() {
        //设置定位回调监听
        mLocationClient?.setLocationListener(mLocationListener)

        mLocationOption?.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mLocationOption?.isOnceLocation = true
        mLocationOption?.isLocationCacheEnable = false //关闭定位缓存
        //给定位客户端对象设置定位参数
        mLocationClient?.setLocationOption(mLocationOption)

        //启动定位
        mLocationClient?.startLocation()
    }

    override fun onStop() {
        super.onStop()

        mLocationClient?.stopLocation()
    }

    override fun onDestroy() {
        super.onDestroy()
        destoryLocation()
    }

    /**
     *内存释放
     */
    private fun destoryLocation() {
        if (null != mLocationListener) {
            mLocationListener = null
        }
        if (null != mLocationClient) {
            mLocationClient?.onDestroy()
            mLocationClient = null
            mLocationOption = null
        }
    }
}